package main.二叉树;

import common.TreeNode;

import java.util.*;

/**
 * @author tmh
 * @date 2024/7/22 14:35
 * @description
 */
public class T199二叉树的右视图 {
    public List<Integer> rightSideView(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }
        List<Integer> result = new ArrayList<>();
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.offer(root);
        while (!deque.isEmpty()) {
            int len = deque.size();
            while (len > 0) {
                TreeNode temp = deque.poll();
                //当队列里面的长度为1的时候，队列里面只剩了右节点
                if (len == 1) {
                    result.add(temp.val);
                }
                if (temp.left != null) {
                    deque.offer(temp.left);
                }
                if (temp.right != null) {
                    deque.offer(temp.right);
                }
                len--;
            }
        }
        return result;
    }
}
